#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/4/29 10:20
# @Author  : CHEN Wang
# @Site    :
# @File    : mail_tool.py
# @Software: PyCharm

"""
脚本说明: 邮件以及钉钉提醒模块
参考：https://www.runoob.com/python/python-email.html
     https://zhuanlan.zhihu.com/p/24180606
"""

import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse
import yagmail
from retrying import retry

monitor_param = {
    # "email": {
    #     "identify": 1,
    #     "subject": None,
    #     "message": None,
    #     "CC": None,
    #     "file": None,
    #     "sender": {"user": 'zjuvincent@163.com',
    #                "password": 'OKAJYVAATMVTNFAL',
    #                "host": 'smtp.163.com'},
    #     "receiver": ['wchen.me@gmail.com'],
    # },

    "email": {
        "identify": 1,
        "subject": None,
        "message": None,
        "CC": None,
        "file": None,
        "sender": {"user": 'web3quant@163.com',
                   "password": 'UBQWJTAECHMFVCNB',
                   "host": 'smtp.163.com'},
    },

    # "email": {
    #     "identify": 1,
    #     "subject": None,
    #     "message": None,
    #     "CC": None,
    #     "file": None,
    #     "sender": {"user": 'dxsl_researcher@163.com',
    #                "password": 'JXFSRTXHMQJJDTGC',
    #                "host": 'smtp.163.com'},
    #     "receiver": ['wchen.me@gmail.com'],
    # },

    "dingding": {
        "identify": 2,
        "message": None,
        "sender": "https://oapi.dingtalk.com/robot/send?access_token=bd25612d1669b2283c12bbee257b32db5089a13201135debf4306c47e56d5b03",
        "secretInfo": "SEC2986333c68d7019d5d7690b41e22eade2a1f69457d16f9ccbe0751cbac261bea",
    }
}
dingdingOut = {
    "text": {"msgtype": "text", "text": {"content": None}, "at": {"atMobiles": None, "isAtAll": False}, },
    "markdown": {"msgtype": "markdown", "markdown": {"title": None, "text": None},
                 "at": {"atMobiles": None, "isAtAll": False}, },
}

monitor_contacts = {
    "fundNet": ["15677390539", "15712162868", "13530707727"],
    "fundNetEmail": ['luodf@thinkive.com', 'daikl@thinkive.com', 'jiangwm@thinkive.com'],
    "fundAnnouncementEmail": ['luodf@thinkive.com', 'daikl@thinkive.com', 'jiangwm@thinkive.com', 'yaohs@thinkive.com'],
    "fundValuationEmail": ['luodf@thinkive.com', 'daikl@thinkive.com', 'jiangwm@thinkive.com',
                           'huangxiong@thinkive.com', 'wangwei@thinkive.com', 'hulw@thinkive.com'],
    "astkHkstexchgrate": ['ouydj@thinkive.com', 'yixin@thinkive.com', 'lijie@thinkive.com'],
    "fund_valuation_aliyun": ['luodf@thinkive.com', 'xiongkai@thinkive.com', 'jianqjb@thinkive.com'],
    "customer_account": ['luodf@thinkive.com', 'xiongkai@thinkive.com'],
    "factor_zs": ['mhy@thinkive.com'],
}

cc_contacts = {
    "fund_valuation_qs": ['daikl@thinkive.com', 'jiangwm@thinkive.com', 'huangxiong@thinkive.com'],
    "customer_account": ['daikl@thinkive.com', 'jiangwm@thinkive.com'],
    "astk_hkstexchgrate": ['xiongkai@thinkive.com', 'daikl@thinkive.com', 'jiangwm@thinkive.com'],
    "fund_valuation_aliyun": ['daikl@thinkive.com', 'jiangwm@thinkive.com'],
    "factor_zs": ['daikl@thinkive.com', 'jiangwm@thinkive.com'],
}


def DataFrame_to_html(message: dict):
    """
    将pd.DataFrame数据传入html表中，并返回html代码

    :param dict message:{'估值':df}
    return str ht
    """
    # warning1 = '<h4 style="color:red;">字体放大 CTRL+SHILT+></h4>'
    # warning2 = '<h4 style="color:red;">字体缩小 CTRL+SHILT+<</h4>'
    body = ''
    for key, value in message.items():
        title = f'<h4 style="color:red;"><font size="8">{key}</font></h4>'
        setting = f'<table border="1" cellspacing="0" cellpadding="1" bordercolor="#00000" width="50%" style="word-wrap:break-word;">'
        df = message[key].copy()
        row = df.index
        col = df.columns
        th = ''
        for j in col:
            th += f'<th nowrap="nowrap"><nobr>{str(j)}</nobr></th>'
        heading = f'<tr>{th}</tr>'
        tr = ''
        for i in row:
            td = ''
            for j in col:
                if df[j][i] is None:
                    td += f'<td>&nbsp;</td>'
                else:
                    td += f'<td nowrap="nowrap"><nobr>{str(df[j][i])}</nobr></td>'
            tr += f'<tr>{td}</tr>'
        table = f'{tr}</table>'
        onetable = title + setting + heading + table
        body += onetable
    # html_message = f'<html><body>{warning1 + warning2 + body}</body></html>'
    html_message = f'<html><body>{body}</body></html>'
    return html_message


def figure_to_html(file_path):
    figure_html = yagmail.inline(file_path)
    return figure_html


class exceptionSimpleModel:
    @retry(stop_max_attempt_number=3)
    def except_main(self, outtype, monitor_param):
        # 单工具提醒：1-邮件提醒，2-钉钉提醒，等；
        # 多工具提醒：11-全部工具，12-等
        if outtype == 1:
            self.exception_email(**monitor_param)
        elif outtype == 2:
            self.dingmessage(**monitor_param)
        elif outtype == 11:
            self.exception_email(**monitor_param)
            self.dingmessage(**monitor_param)

    def exception_email(self, identify, subject, message, sender=None, receiver=None, CC=None, file=None):
        """

        :param int identify: 邮件标识：1-发送邮件，0-不发送
        :param str subject: 邮件主题
        :param str message: 邮件主体内容，如果换行，用多个单引号，如：contents = ['This is the body', 'hello,
        you are good!']
        :param dict sender: 数据类型：字典，例子：{user="user@126.com", password="1234", host='smtp.126.com'}
        注意：个人邮箱password是授权码，不是密码，目前默认邮箱是：腾讯企业邮箱
        :param str or list receiver: 收件人，单个收件人数据类型：字符串, 多个收件人数据类型：列表
        :param str or list CC: 抄送人，单个收件人数据类型：字符串, 多个收件人数据类型：列表
        :param list file: 附件，数据类型：列表
        :return:
            for example: exceptionSimple.exception_email(identify=1,  message='test', subject='aa')
                 sender, receiver:默认是系统参数

                 邮件内容：提供html格式，示例：
                 contents = [
                            "<h1 style='color:red'>一级标题</h1>",#可以是html语言
                            'beauty.jpg',#可以是文件,以附件形式发送
                            # yagmail.inline('beauty.jpg'),# 这样的话,图片会内嵌到正文
                            'hello world', #可以是普通文本
                            ]
        """

        if sender is None:
            sender = {"user": 'zjuvincent@163.com', "password": 'OKAJYVAATMVTNFAL', "host": 'smtp.163.com'}
        if receiver is None:
            receiver = ['zjuvincent@163.com']

        if identify == 1:
            yagUesr = yagmail.SMTP(**sender)
            yagUesr.send(to=receiver, subject=subject, contents=message, cc=CC, attachments=file)
        elif identify == 0:
            pass
        print('邮件发送成功')

    def dingmessage(self, identify, message, sender, secretInfo):
        '''

        Args:
            identify: 发送钉钉消息模式：1-非验签；2-验签：3-占位调试用，不发送钉钉消息
            message: 发送的内容
            sender: 发送方信息，即钉钉token
            secretInfo: 发送详情，需注意：1.换行(\n\n)：2.转义字符

        Returns:
            发送是否成功

        '''
        headers = {"Content-Type": "application/json", "Charset": "UTF-8"}

        if identify == 1:
            pass
        elif identify == 2:
            # token
            timestamp = str(round(time.time() * 1000))
            secret = secretInfo
            secret_enc = secret.encode('utf-8')
            string_to_sign = '{}\n{}'.format(timestamp, secret)
            string_to_sign_enc = string_to_sign.encode('utf-8')
            hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
            sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
            sender = sender + f'&timestamp={timestamp}&sign={sign}'

        elif identify == 0:
            pass

        # 对请求的数据进行json封装
        message_json = json.dumps(message)
        # 发送请求，url为webhook
        try:
            resultStatus = requests.post(url=sender, data=message_json, headers=headers)
            print(resultStatus.text)
        except Exception as err:
            print(err)


if __name__ == '__main__':
    import pandas as pd
    # message = '<style class="fox_global_style"> div.fox_html_content { line-height: 1.5;} /* 一些默认样式 */ blockquote ' \
    #           '{ margin-Top: 0px; margin-Bottom: 0px; margin-Left: 0.5em } ol, ul { margin-Top: 0px; margin-Bottom: 0px; ' \
    #           'list-style-position: inside; } p { margin-Top: 0px; margin-Bottom: 0px } </style><div><table border="1" ' \
    #           'bordercolor="#000000" cellpadding="2" cellspacing="0" style="font-size: 10pt; border-collapse:collapse;" ' \
    #           'width="50%"> <tbody><tr> <td width="20%" nowrap=""><font size="2" face="Verdana"><div>&nbsp;</div></font></td> ' \
    #           '<td width="20%" nowrap=""><font size="2" face="Verdana"><div>&nbsp;</div></font></td> <td width="20%" nowrap=""' \
    #           '><font size="2" face="Verdana"><div>&nbsp;</div></font></td> <td width="20%" nowrap=""><font size="2" ' \
    #           'face="Verdana"><div>&nbsp;</div></font></td> <td width="20%" nowrap=""><font size="2" face="Verdana">' \
    #           '<div>&nbsp;</div></font></td> </tr> <tr> <td width="20%" nowrap=""><font size="2" face="Verdana"><div>' \
    #           '&nbsp;</div></font></td> <td width="20%" nowrap=""><font size="2" face="Verdana"><div>&nbsp;</div></' \
    #           'font></td> <td width="20%" nowrap=""><font size="2" face="Verdana"><div>&nbsp;</div></font></td> <td ' \
    #           'width="20%" nowrap=""><font size="2" face="Verdana"><div>&nbsp;</div></font></td> <td width="20%" ' \
    #           'nowrap=""><font size="2" face="Verdana"><div>&nbsp;</div></font></td> </tr></tbody></table></div>' \
    #           '<hr style="width: 210px; height: 1px;" id="FMSigSeperator" align="left" color="#b5c4df" size="1"> ' \
    #           '<div><div style="font-family: verdana; font-size: 13.3333px; line-height: 26.6667px;">' \
    #           '<a href="mailto:yaohs@thinkive.com" class="" style="text-decoration: none !important; font-size: 13.3333px;' \
    #           ' background-color: transparent;">wchen.me@gmail.com	</a><span style="color: rgb(0, 0, 0); ' \
    #           'font-size: 13.3333px; background-color: rgba(0, 0, 0, 0);">&nbsp;</span></div><div style="font-family: ' \
    #           'verdana; font-size: 13.3333px; line-height: 26.6667px;"><span style="font-family: Verdana; ' \
    #           'font-size: 14px; line-height: normal;">投研组 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ' \
    #           '&nbsp; &nbsp; &nbsp;	</span><br style="font-family: Verdana; font-size: 14px; line-height: normal;">' \
    #           '<span style="font-family: Verdana; font-size: 14px; line-height: normal;">地心算力有限公司' \
    #           '</span><br style="font-family: Verdana; font-size: 14px; line-height: normal;"><span style="font-family: ' \
    #           'Verdana; font-size: 14px; line-height: normal;">地址：	</span><span style="color: rgb(0, 0, 0); ' \
    #           'font-family: Verdana; font-size: 14px; line-height: normal; background-color: rgba(0, 0, 0, 0);">' \
    #           '杭州萧山区	</span><br style="font-family: Verdana; font-size: 14px; ' \
    #           'line-height: normal;"><span style="font-family: Verdana; font-size: 14px; line-height: normal;">' \
    #           '网址：	</span><a href="http://www.dxsl.com/" target="_blank" style="text-decoration: none ' \
    #           '!important; font-family: Verdana; font-size: 14px; line-height: normal; outline: none; color: ' \
    #           'rgb(44, 74, 119);">http://www.***.com	</a><span style="font-family: Verdana; ' \
    #           'font-size: 14px; line-height: normal;">&nbsp;</span></div><div style="font-family: verdana; ' \
    #           'font-size: 13.3333px; line-height: 26.6667px;"><span style="font-family: Verdana; font-size: ' \
    #           '14px; line-height: normal;">电话：******</span></div></div>'
    df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])
    message = DataFrame_to_html({'test': df})
    figure = figure_to_html(r'E:\指标测试-第四版\all_selected_strategy_signal-2022-01-18\综合信号-signal_backtest.png')

    exceptionSimple = exceptionSimpleModel()
    # 测试邮件
    emailParam = monitor_param["email"]
    emailParam["subject"] = "你好"
    emailParam["message"] = [message, figure]
    # emailParam["message"] = '呦呦，切克闹，优秀！'
    emailParam["file"] = [r'E:\指标数据\all_ohlcv.csv']  # 添加附件
    emailParam["receiver"] = ['wchen.me@gmail.com']
    exceptionSimple.except_main(1, emailParam)

    # 测试钉钉
    # dingdOut = dingdingOut["text"]
    # dingdOut["text"]["content"] = 'stg-[正常]数据监控 \n secret验签测试 \n '
    # monitor_param['dingding']["message"] = dingdOut
    # print(monitor_param["dingding"])
    #
    # exceptionSimple.except_main(2, monitor_param)
